package agent

import (
	"dragonfly/common/tcp"
	"dragonfly/common/types"
)

type callback struct {
}

func (cb *callback) OnConnected(conn *tcp.TCPConn) {
	agent.log.Info().Msgf("callback: %s connected.", conn.GetRemoteAddr().String())
}

//链接断开回调
func (cb *callback) OnDisconnected(conn *tcp.TCPConn) {
	agent.log.Info().Msgf("callback: %s disconnect.", conn.GetRemoteAddr().String())
}

//错误回调
func (cb *callback) OnError(err error) {
	agent.log.Error().Msgf("callback: %v .", err)
}

//消息处理回调
func (cb *callback) OnMessage(conn *tcp.TCPConn, p tcp.Packet) {
	defer func() {
		if r := recover(); r != nil {
			agent.log.Error().Msgf("Recovered in OnMessage: %v", r)
		}
	}()
	pkt := p.(*tcp.DefaultPacket)
	cb.dispatch(conn, pkt)
}

func (cb *callback) dispatch(conn *tcp.TCPConn, pkt *tcp.DefaultPacket) {
	switch pkt.Type {
	case types.MsgGetHeartbeat:
		hb := types.HeartBeat{
			Alive:   true,
			Message: "PONG",
		}

		agent.log.Debug().Msgf("%s, %s", types.MsgTextMap[pkt.Type], string(pkt.Body))
		if err := conn.AsyncWritePacket(
			tcp.NewDefaultPacket(
				types.MsgSendHeartbeat,
				hb.Encode(),
			),
		); err != nil {
			agent.log.Error().Msgf("send heartbeat failed. %s", err)
		}
	default:
		agent.log.Warn().Msgf("%s no callback", types.MsgTextMap[pkt.Type])
		conn.Close()
	}
}
